package com.example.ivideo_2211a

import com.example.common.mvi.BaseRepository
import com.example.common.mvi.NetworkResult
import com.example.ivideo_2211a.fabu.VideoFaEntityItem
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import com.example.common.mvi.NetworkConfig
import retrofit2.http.GET
import retrofit2.http.Query

interface VideoDetailApi {
    @GET("api/videos/findAll")
    suspend fun getVideoList(@Query("page") page: Int, @Query("size") size: Int): VideoListResponse
}

data class VideoListResponse(
    val code: Int,
    val msg: String,
    val data: List<VideoFaEntityItem>
)

class VideoDetailRepository : BaseRepository() {
    private val api: VideoDetailApi by lazy {
        Retrofit.Builder()
            .baseUrl("http://10.161.9.80:7015/")
            .client(NetworkConfig.createOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create(NetworkConfig.createGson()))
            .build()
            .create(VideoDetailApi::class.java)
    }

    /**
     * 获取视频详情
     */
    fun getVideoDetail(videoId: Int): Flow<NetworkResult<VideoFaEntityItem>> {
        return safeApiCall {
            Response.success(api.getVideoList(1, 10))
        }.map { result ->
            when (result) {
                is NetworkResult.Success -> {
                    val response = result.data
                    if (response.code == 200) {
                        // 查找匹配的视频
                        val video = response.data.find { it.videoId == videoId }
                        if (video != null) {
                            NetworkResult.Success(video)
                        } else {
                            NetworkResult.Error(Exception("未找到该视频"))
                        }
                    } else {
                        NetworkResult.Error(Exception(response.msg))
                    }
                }
                is NetworkResult.Error -> result
                is NetworkResult.Loading -> result
            }
        }
    }
}